const express = require('express');
const CacheManager = require('./cache-manager');
const ClusterManager = require('./cluster-manager');
const config = require('./config');

class SimpleDistCache {
    constructor(port = 3000) {
        this.port = port;
        this.app = express();
        this.cacheManager = new CacheManager();
        this.clusterManager = new ClusterManager(port);
        
        this.setupMiddleware();
        this.setupRoutes();
    }

    setupMiddleware() {
        this.app.use(express.json());
        this.app.use(express.urlencoded({ extended: true }));
    }

    setupRoutes() {
        // 读取缓存
        this.app.get('/cache/:key', async (req, res) => {
            try {
                const { key } = req.params;
                const value = await this.cacheManager.get(key);
                
                if (value === null) {
                    return res.status(404).json({ error: 'Key not found' });
                }
                
                res.json({ key, value });
            } catch (error) {
                res.status(500).json({ error: error.message });
            }
        });

        // 写入缓存
        this.app.post('/cache', async (req, res) => {
            try {
                const { key, value, ttl } = req.body;
                
                if (!key || value === undefined) {
                    return res.status(400).json({ error: 'Key and value are required' });
                }
                
                await this.cacheManager.set(key, value, ttl);
                
                // 同步到其他节点
                await this.clusterManager.syncSet(key, value, ttl);
                
                res.json({ success: true, key, value, ttl });
            } catch (error) {
                res.status(500).json({ error: error.message });
            }
        });

        // 删除缓存
        this.app.delete('/cache/:key', async (req, res) => {
            try {
                const { key } = req.params;
                await this.cacheManager.delete(key);
                
                // 同步删除到其他节点
                await this.clusterManager.syncDelete(key);
                
                res.json({ success: true, key });
            } catch (error) {
                res.status(500).json({ error: error.message });
            }
        });

        // 获取所有节点信息
        this.app.get('/nodes', (req, res) => {
            res.json({
                currentNode: this.clusterManager.currentNode,
                nodes: this.clusterManager.getNodes()
            });
        });

        // 健康检查
        this.app.get('/health', (req, res) => {
            res.json({ status: 'healthy', timestamp: Date.now() });
        });

        // 集群同步接口
        this.app.post('/sync/set', async (req, res) => {
            try {
                const { key, value, ttl } = req.body;
                await this.cacheManager.set(key, value, ttl);
                res.json({ success: true });
            } catch (error) {
                res.status(500).json({ error: error.message });
            }
        });

        this.app.post('/sync/delete', async (req, res) => {
            try {
                const { key } = req.body;
                await this.cacheManager.delete(key);
                res.json({ success: true });
            } catch (error) {
                res.status(500).json({ error: error.message });
            }
        });
    }

    async start() {
        await this.cacheManager.init();
        await this.clusterManager.init();
        
        this.app.listen(this.port, () => {
            console.log(`SimpleDistCache 运行在端口 ${this.port}`);
            console.log(`节点ID: ${this.clusterManager.currentNode.id}`);
            console.log(`访问 http://localhost:${this.port}/health 检查服务状态`);
        });
    }
}

// 启动服务
const port = process.env.PORT || 3000;
const cache = new SimpleDistCache(port);
cache.start().catch(console.error);

module.exports = SimpleDistCache;
